package com.coderknock.jedis.executor;

import com.coderknock.jedis.function.JedisExecutorInterface;
import com.coderknock.jedis.function.JedisExecutorNotReturnInterface;
import com.coderknock.jedis.function.JedisExecutorPipelineInterface;
import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.Pipeline;

import java.io.IOException;
import java.util.List;
import java.util.Properties;

/**
 * <p></p>
 *
 * @author 三产
 * @version 1.0
 * @date 2017-06-22
 * @QQGroup 213732117 【购买了讲座的童鞋请加 660767582 验证信息输入 sf 用户名】
 * @website http://www.coderknock.com
 * @copyright Copyright 2017 拿客 coderknock.com  All rights reserved.
 * @since JDK 1.8
 */
public class JedisExecutor {
    private static Properties properties = new Properties();

    private static GenericObjectPoolConfig poolConfig = new GenericObjectPoolConfig();
    // 初始化Jedis连接池
    //private static JedisPool jedisPool = new JedisPool(poolConfig, "127.0.0.1", 6379, 1000, "admin123");
    private static JedisPool jedisPool = new JedisPool(poolConfig, "192.168.31.223", 6379, 100000);

    /**
     * 普通操作执行
     *
     * @param executor
     * @param <T>
     * @return
     */
    public static <T extends Object> T execute(JedisExecutorInterface<T> executor) {
        // 返回值
        T Object;

        try (   // 获取连接池里的连接  这里会自动释放资源
                Jedis jedis = jedisPool.getResource();
        ) {
            // 业务操作
            Object = executor.execute(jedis);
        }
        return Object;
    }


    /**
     * 普通操作执行 没有返回值NR not return
     *
     * @param executor
     */
    public static void executeNR(JedisExecutorNotReturnInterface executor) {
        // 返回值
        try (   // 获取连接池里的连接  这里会自动释放资源
                Jedis jedis = jedisPool.getResource();
        ) {
            // 业务操作
            executor.execute(jedis);
        }
    }

    /**
     * 通过 pipeline 执行操作，并将所有的返回值以List的形式返回
     *
     * @param executor
     * @return
     */
    public static List<Object> executeWithPipline(JedisExecutorPipelineInterface executor) {
        try (   // 获取连接池里的连接
                Jedis jedis = jedisPool.getResource();
                Pipeline pipeline = jedis.pipelined();
        ) {

            // 业务操作
            executor.execute(pipeline);
            return pipeline.syncAndReturnAll();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 通过 pipeline 执行操作，但是没有返回值 NR not return
     *
     * @param executor
     */
    public static void executeWithPiplineNR(JedisExecutorPipelineInterface executor) {
        try (   // 获取连接池里的连接
                Jedis jedis = jedisPool.getResource();
                Pipeline pipeline = jedis.pipelined();
        ) {

            // 业务操作
            executor.execute(pipeline);
            pipeline.sync();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
